package com.zlkj.pro.modular.business.controller;

import cn.stylefeng.roses.kernel.auth.api.AuthServiceApi;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.auth.api.password.PasswordStoredEncryptApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.auth.LoginRequest;
import cn.stylefeng.roses.kernel.auth.api.pojo.auth.LoginResponse;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import cn.stylefeng.roses.kernel.system.api.exception.SystemModularException;
import cn.stylefeng.roses.kernel.system.api.exception.enums.user.SysUserExceptionEnum;
import cn.stylefeng.roses.kernel.system.api.pojo.user.SysUserDTO;
import cn.stylefeng.roses.kernel.system.api.pojo.user.request.SysUserRequest;
import cn.stylefeng.roses.kernel.system.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import com.zlkj.pro.core.consts.ProjectConstants;
import com.zlkj.pro.core.exception.BusinessException;
import com.zlkj.pro.modular.admin.entity.User;
import com.zlkj.pro.modular.admin.mapper.UserMapper;
import com.zlkj.pro.modular.admin.model.dto.UserDTO;
import com.zlkj.pro.modular.business.entity.AgentEntity;
import com.zlkj.pro.modular.business.service.AgentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.BUSINESS_EXCEPTION;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@ApiResource(name = "用户", path = "/login")
public class WebLoginController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private AuthServiceApi authServiceApi;
    @Autowired
    private AgentService agentService;
    @Autowired
    private UserMapper userMapper;


    @PostResource(name = "登陆（分离版）", path = "/loginApi", requiredLogin = false, requiredPermission = false, responseClass = LoginResponse.class)
    public ResponseData loginApi(@RequestBody LoginRequest loginRequest) {
        if (StringUtils.isEmpty(loginRequest.getAccount())) {
            throw new BusinessException(BUSINESS_EXCEPTION, "账号不能为空");
        }
        if (StringUtils.isEmpty(loginRequest.getPassword())) {
            throw new BusinessException(BUSINESS_EXCEPTION, "密码不能为空");
        }

        loginRequest.setCreateCookie(false);
        LoginResponse loginResponse = authServiceApi.login(loginRequest);
        if(!loginResponse.getLoginUser().getAccount().equals(loginRequest.getAccount())){
            throw new BusinessException(BUSINESS_EXCEPTION, loginRequest.getAccount() + " 用户不存在");
        }
        Long userId = loginResponse.getLoginUser().getUserId();

        UserDTO dto = new UserDTO();
        dto.setUserId(userId);
        extracted(dto);
        if (dto.getRoleId() != null && dto.getRoleId() == 5L) {
            throw new BusinessException(BUSINESS_EXCEPTION, "请您使用小程序登录");
        }

        // 代理商禁用后 所有账号禁止登录
        if (dto.getRoleId() != null && (dto.getRoleId() == 3L || dto.getRoleId() == 4L || dto.getRoleId() == 5L)) {
            // 查询当前用户信息
            User user = userMapper.selectById(userId);
            if (user != null && user.getAgentId() != null) {
                AgentEntity agent = agentService.getById(user.getAgentId());
                if (agent != null && agent.getStatusFlag().equals(2)) {
                    throw new BusinessException(BUSINESS_EXCEPTION, "您所在代理商已禁用");
                }
            }
        }

        return new SuccessResponseData(loginResponse);
    }

    private void extracted(UserDTO dto) {
        SysUserRequest sysUserRequest = new SysUserRequest();
        sysUserRequest.setUserId(dto.getUserId());
        SysUserDTO currentUser = sysUserService.detail(sysUserRequest);
        Long roleId = currentUser.getGrantRoleIdList().get(0);
        if (ProjectConstants.ROLE_ID_BMSH_MANAGER.equals(roleId)) {
            dto.setRoleId(1L);
        } else if (ProjectConstants.ROLE_ID_BMSH_YG.equals(roleId)) {
            dto.setRoleId(2L);
        } else if (ProjectConstants.ROLE_ID_AGENT_MANAGER.equals(roleId)) {
            dto.setRoleId(3L);
        } else if (ProjectConstants.ROLE_ID_JL.equals(roleId)) {
            dto.setRoleId(4L);
        } else if (ProjectConstants.ROLE_ID_YG.equals(roleId)) {
            dto.setRoleId(5L);
        }
    }


    @Resource
    private PasswordStoredEncryptApi passwordStoredEncryptApi;

    /**
     * 修改密码
     *
     * @author liyang
     * @date 2024/6/27 13:50
     */
    @PostResource(name = "个人信息_修改密码", path = "/sysUser/updatePassword", requiredPermission = false)
    public ResponseData updatePwd(@RequestBody @Validated(SysUserRequest.updatePwd.class) SysUserRequest sysUserRequest) {
        // 获取当前用户的userId
        LoginUser loginUser = LoginContext.me().getLoginUser();
        sysUserRequest.setUserId(loginUser.getUserId());

        SysUser sysUser = sysUserService.getById(sysUserRequest.getUserId());

        // 新密码与原密码相同
        if (sysUserRequest.getNewPassword().equals(sysUserRequest.getPassword())) {
            throw new SystemModularException(SysUserExceptionEnum.USER_PWD_REPEAT);
        }

        // 原密码错误
        if (!passwordStoredEncryptApi.checkPassword(sysUserRequest.getPassword(), sysUser.getPassword())) {
            throw new SystemModularException(SysUserExceptionEnum.USER_PWD_ERROR);
        }

        sysUser.setPassword(passwordStoredEncryptApi.encrypt(sysUserRequest.getNewPassword()));
        sysUserService.updateById(sysUser);

        return new SuccessResponseData();
    }

}
